package com.xn.app.muying.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xn.app.muying.MainActivity;
import com.xn.app.muying.MuYingApplication;
import com.xn.app.muying.R;
import com.xn.app.muying.activity.ChanJianListActivity;
import com.xn.app.muying.activity.ChanJianXiangQingActivity;
import com.xn.app.muying.activity.DoctorActivity;
import com.xn.app.muying.activity.KePuActivity;
import com.xn.app.muying.activity.MonitorActivity;
import com.xn.app.muying.activity.MonitorSelectActivity;
import com.xn.app.muying.activity.YunQiXuanZeActivity;
import com.xn.app.muying.adpter.HomeAdpter;
import com.xn.app.muying.adpter.HomeTopViewPagerAdapter;
import com.xn.app.muying.bean.HomeTopBean;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AutoTextView;
import com.xn.app.muying.util.Constants;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Request;

/**
 * Created by Administrator on 2016/10/10.
 */
public class HomeFragment extends Fragment implements HttpUtil.OnGetDataListener, View.OnClickListener {
    private Handler handler = new Handler();
    private ViewPager vp;
    private AutoTextView message_tv;
    private int index = 0;
    private ArrayList<String> shuju;
    boolean isLook = false;
    boolean isLogin = false;

    private LinearLayout yunqishezhi_ll;
    public static TextView yunqishezhi_tv;
    private ImageView yunqishezhi_iv;
    private String nextAntenatalCareId;
    private boolean sign;
    private String antenatalCareHospitalId;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.home_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isLogin = Constants.getBooleanByName(MainActivity.mActivity, "isLogin");
        ListView listView = (ListView) view.findViewById(R.id.home_fragment_floor);
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.home_fragment_floor_one, null);
        vp = (ViewPager) inflate.findViewById(R.id.home_fragment_floor_one_vp);
        LinearLayout monitor_ll = (LinearLayout) inflate.findViewById(R.id.home_fragment_monitor);
        LinearLayout yunqian_ll = (LinearLayout) inflate.findViewById(R.id.home_fragment_yunqian);
        LinearLayout yunqi_ll = (LinearLayout) inflate.findViewById(R.id.home_fragment_yunqi);
        LinearLayout doctor_ll = (LinearLayout) inflate.findViewById(R.id.home_fragment_doctor);
        message_tv = (AutoTextView) inflate.findViewById(R.id.home_xiaoxi_tv);
        yunqishezhi_ll = (LinearLayout) inflate.findViewById(R.id.home_yunqishezhi_ll);
        yunqishezhi_tv = (TextView) inflate.findViewById(R.id.home_yunqishezhi_tv);
        yunqishezhi_iv = (ImageView) inflate.findViewById(R.id.home_yunqishezhi_iv);

        vp.setBackgroundResource(R.mipmap.img_0016);

        monitor_ll.setOnClickListener(this);
        yunqian_ll.setOnClickListener(this);
        yunqi_ll.setOnClickListener(this);
        doctor_ll.setOnClickListener(this);
        yunqishezhi_ll.setOnClickListener(this);
        message_tv.setOnClickListener(this);
        listView.addHeaderView(inflate);
        if (isLogin) {
            setmessage();
            setMineInfo();
        }

        HttpUtil.getData(APIMethod.Home_Top, handler, this);

        shuju = new ArrayList();
        int a = 0;
        for (; a < 10; a++) {
            shuju.add(a + "");
        }

        message_tv.setText("设置预产期，开启智能产检提醒");
        HomeAdpter homeAdapter = new HomeAdpter(getActivity(), shuju);
        listView.setAdapter(homeAdapter);

    }

    @Override
    public void onStart() {
        super.onStart();
        setmessage();
    }

    private void setmessage() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    String tokens = Constants.getStringByName(getActivity(), "yonghu");
                    Type type1 = new TypeToken<HashMap<String, String>>() {
                    }.getType();
                    HashMap<String, String> token = new Gson().fromJson(tokens, type1);
                    if (token == null) {
                    } else {
                        Request request = new Request.Builder().url("http://apitest.beierbaby.com/api/antenatalcares/user/pregnancy-status").addHeader("Authorization", "Bearer " + token.get("access_token")).get().build();
                        okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();

                        int code = response.code();
                        String bodys = response.body().string();
                        onJsonInfo(bodys);//解析首页的消息
                        Log.i("code==", "code==" + code);
                        Log.i("bodys=qq=", bodys);
                        if (code == 204 || code == 200) {
                            Message msg2 = new Message();
                            msg2.what = 0;
                            msg2.obj = bodys;
                            handler1.sendMessage(msg2);
                        } else {
                            Message msg1 = new Message();
                            msg1.what = 1;
                            msg1.arg1 = code;
                            msg1.obj = bodys;
                            handler1.sendMessage(msg1);
                        }

                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void onJsonInfo(String bodys) {
        try {
            JSONObject jsonObject = new JSONObject(bodys);
            final String tipMessage = jsonObject.optString("tipMessage");
            String pregnancyStatus = jsonObject.optString("pregnancyStatus");
            nextAntenatalCareId = jsonObject.optString("nextAntenatalCareId");

            if (pregnancyStatus.equals("0")) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        yunqishezhi_tv.setText("备孕期");
                        message_tv.setText(tipMessage);
                    }
                });

            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        yunqishezhi_tv.setText("怀孕期");
                        message_tv.setText(tipMessage);
                    }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
//                    ToastUtil.showToast(getActivity(), "修改成功");
                    break;
                case 1:
//                    ToastUtil.showToast(getActivity(), "修改失败");
                    break;
            }
        }
    };


    //获取用户消息
    private void setMineInfo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    String tokens = Constants.getStringByName(getActivity(), "yonghu");
                    Type type1 = new TypeToken<HashMap<String, String>>() {
                    }.getType();

                    HashMap<String, String> token = new Gson().fromJson(tokens, type1);
                    if (token == null) {

                    } else {
                        Request request = new Request.Builder().url("http://apitest.beierbaby.com/api/account/userinfo").addHeader("Authorization", "Bearer " + token.get("access_token")).get().build();
                        okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();

                        int code = response.code();
                        String bodys = response.body().string();
                        onJsonMine(bodys);
                    }
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        }).start();
    }

    private void onJsonMine(String bodys) {
        try {
            JSONObject jsonObject = new JSONObject(bodys);
            antenatalCareHospitalId = jsonObject.optString("antenatalCareHospitalId");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    //解析Banner的数据
    @Override
    public void onJsonData(String data) {
        try {
            JSONArray array = new JSONArray(data);
            final ArrayList<HomeTopBean> arrayList = new ArrayList<>();
            for (int i = 0; i < array.length(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                String pictureUrl = jsonObject.optString("pictureUrl");
                String id = jsonObject.optString("id");
                HomeTopBean homeTopBean = new HomeTopBean();
                homeTopBean.setPictureUrl(pictureUrl);
                homeTopBean.setId(id);
                arrayList.add(homeTopBean);

            }

            ArrayList<View> list = new ArrayList<>();
            for (int i = 0; i < arrayList.size(); i++) {
                ImageView iv = new ImageView(getActivity());
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
                iv.setLayoutParams(params);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                iv.setImageResource(R.mipmap.img_0016);
                iv.setTag(arrayList.get(i).getPictureUrl());
                HttpUtil.getBitMap(arrayList.get(i).getPictureUrl(), handler, iv);
                if (iv != null) {
                    list.add(iv);
                }


            }
            HomeTopViewPagerAdapter pagerAdapter = new HomeTopViewPagerAdapter(list);
            vp.setAdapter(pagerAdapter);
            new MyThread().start();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.home_fragment_monitor:
                intent.setClass(getActivity(), MonitorSelectActivity.class);
                startActivity(intent);
                break;
            case R.id.home_fragment_yunqian:
                intent.setClass(getActivity(), KePuActivity.class);
                startActivity(intent);
                break;
            case R.id.home_fragment_yunqi:
                if (isLogin) {
                    intent.setClass(getActivity(), ChanJianListActivity.class);

                    if (nextAntenatalCareId.equals("null")) {
                        Toast.makeText(getActivity(), "请正确设置怀孕信息", Toast.LENGTH_SHORT).show();
                    } else {

                        intent.putExtra("hospitalId", antenatalCareHospitalId);
                        startActivity(intent);
                    }
                } else {
                    Toast.makeText(getActivity(), "请登录", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.home_fragment_doctor:
                intent.setClass(getActivity(), DoctorActivity.class);
                startActivity(intent);
                break;

            case R.id.home_yunqishezhi_ll:
                if (isLogin) {
                    intent.putExtra("PAGE_INTENT", "HomeFragment");
//                    intent.putExtra("home_page", "1");
                    intent.setClass(getActivity(), YunQiXuanZeActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), "请登录", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.home_xiaoxi_tv:
                if (!nextAntenatalCareId.equals("null")) {
                    Log.i("nextAntenatalCareId", nextAntenatalCareId);
                    intent.putExtra("nextAntenatalCareId", nextAntenatalCareId);
                    intent.setClass(getActivity(), ChanJianXiangQingActivity.class);
                    startActivity(intent);
                }

                break;

        }
    }


    //ViewPager实现循环播放的线程
    class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (true) {
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        int i = vp.getCurrentItem();
                        if (i == 3) {
                            vp.setCurrentItem(0, true);
                        } else {
                            vp.setCurrentItem(++i, true);
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        isLook = true;
    }

    @Override
    public void onPause() {
        super.onPause();
        isLook = false;
    }

    @Override
    public void onStop() {
        super.onStop();
        isLook = false;
    }

    @Override
    public void onDestroy() {
//        getActivity().unregisterReceiver(myReceiver);
        super.onDestroy();
    }

}
